package libs

import (
	"github.com/apache/rocketmq-clients/golang/v5"
	"github.com/apache/rocketmq-clients/golang/v5/credentials"
	"os"
)

const (
	// 事物消息
	// ./mqadmin updateSubGroup -n localhost:9876 -c DefaultCluster -g transaction_group
	TransactionGroup = "transaction_group"
	// ./mqadmin updatetopic -n localhost:9876 -t transaction -c DefaultCluster -a +message.type=TRANSACTION
	TransactionTopic = "transaction"
)

func NewTransactionProducer(transactionChecker *golang.TransactionChecker) (golang.Producer, error) {
	// log to console
	os.Setenv("mq.consoleAppender.enabled", "true")
	golang.ResetLogger()
	// In most case, you don't need to create many producers, singleton pattern is more recommended.
	return golang.NewProducer(
		&golang.Config{
			Endpoint: RocketmqConfig.Endpoint,
			Credentials: &credentials.SessionCredentials{
				AccessKey:    RocketmqConfig.AccessKey,
				AccessSecret: RocketmqConfig.AccessSecret,
			},
		},
		// 定义 MQ 回查方法，用于 MQ 异常后收不到消息，而回查订单是否支付成功
		//golang.WithTransactionChecker(&golang.TransactionChecker{
		//	Check: func(msg *golang.MessageView) golang.TransactionResolution {
		//		log.Printf("check transaction message: %v", msg)
		//		if true { // 支付成功
		//			return golang.COMMIT
		//		} else { // 支付失败
		//			return golang.ROLLBACK
		//		}
		//	},
		//}),
		golang.WithTransactionChecker(transactionChecker),
		golang.WithTopics(TransactionTopic),
	)
}
